import {
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CustomerQuotationReply } from './entities/customer-quotation-reply.entity';
import { CreateCustomerQuotationReplyDto } from './dto/create-customer-quotation-reply.dto';
import { UpdateCustomerQuotationReplyDto } from './dto/update-customer-quotation-reply.dto';
import { UploadPicturesService } from '../common/upload/upload-pictures.service';

@Injectable()
export class CustomerQuotationReplyService {
  constructor(
    @InjectRepository(CustomerQuotationReply)
    private customerQuotationReplyRepository: Repository<CustomerQuotationReply>,
    private uploadPicturesService: UploadPicturesService,
  ) {}



  async findByQuoteid(quoteid: string): Promise<CustomerQuotationReply[]> {
    const replies = await this.customerQuotationReplyRepository.find({
      where: { quoteid },
      order: { replytime: 'ASC' },
    });

    // 为每个回复获取图片
    for (const reply of replies) {
      if (reply.picture) {
        console.log('=== 客户报价回复图片调试 ===');
        console.log('回复 picture 字段:', reply.picture);
        reply['uploadpictures'] = await this.uploadPicturesService.findByServiceId(reply.picture);
        console.log('查询到的图片:', reply['uploadpictures']);
      }
    }

    return replies;
  }

  async findById(id: number): Promise<CustomerQuotationReply> {
    const reply = await this.customerQuotationReplyRepository.findOne({
      where: { _Identify: id },
    });
    if (!reply) {
      throw new NotFoundException(`Customer quotation reply with id ${id} not found`);
    }
    return reply;
  }









  // 测试方法：直接查询图片记录
  async testFindImageByServiceId(serviceId: string): Promise<any> {
    console.log('=== 测试图片查询 ===');
    console.log('测试 serviceId:', serviceId);
    
    try {
      // 直接使用原始SQL查询
      const result = await this.uploadPicturesService['uploadPicturesRepository']
        .createQueryBuilder('up')
        .where('up.serviceId = :serviceId', { serviceId })
        .getMany();
      
      console.log('原始查询结果:', result);
      return result;
    } catch (error) {
      console.error('查询错误:', error);
      return [];
    }
  }
} 